package com.example.apiversioncontroldemo.config;

import com.example.apiversioncontroldemo.util.vcon.ApiVersion;
import com.example.apiversioncontroldemo.util.vcon.ApiVersionCondition;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * @author chen.cr
 * @since 2023/10/19
 */
@Configuration
public class WebConfig2 implements WebMvcConfigurer {



    @Configuration
    @ConditionalOnWebApplication
    @ConfigurationProperties(prefix = "server.api")
    public static class URIVersionHandleConfig implements WebMvcRegistrations {

        @Setter
        @Getter
        private int minimumVersion;

        @Override
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {

            return new RequestMappingHandlerMapping() {
                /**
                 * @param handlerType 创建 RequestCondition 的处理类
                 * @return
                 */
                @Override
                protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
                    ApiVersion annotation = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
                    return annotation == null ? null : new ApiVersionCondition(annotation.version(), minimumVersion);
                }

                /**
                 * @param method 创建 RequestCondition 的处理方法
                 * @return
                 */
                @Override
                protected RequestCondition<?> getCustomMethodCondition(Method method) {
                    ApiVersion annotation = AnnotationUtils.findAnnotation(method, ApiVersion.class);
                    return annotation == null ? null : new ApiVersionCondition(annotation.version(), minimumVersion);
                }
            };
        }

    }

}
